package com.most.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.most.api.UserVO;
import com.most.auth.dto.Role;
import com.most.auth.dto.User;
import com.most.auth.dto.UserRole;
import com.most.auth.mapper.UserMapper;
import com.most.auth.service.RoleService;
import com.most.auth.service.UserRoleService;
import com.most.auth.service.UserService;
import com.most.auth.util.SaltUtil;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {


    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;
    @Override
    public List<Role> findRoleByUserId(Long userId) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<UserRole> list = userRoleService.list(queryWrapper);
        List<Long> collect = list.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        return  roleService.listByIds(collect);
    }

    @Override
    public List<String> getPermissionsById(Long id) {

        return new ArrayList<>();
    }

    @Override
    public UserVO findOneByUserName(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User one = this.getOne(queryWrapper);
        if (one==null){
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(one,userVO);
        return userVO;
    }

    @Override
    public void setPassword(User user) {
        String salt = SaltUtil.getSalt(8);
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(md5Hash.toHex());
        user.setSalt(salt);
    }
    @Override
    public String getPassword(String password,String salt) {
        Md5Hash md5Hash = new Md5Hash(password, salt, 1024);
        return md5Hash.toHex();
    }
}
